import { Button, Card, Space, Popconfirm } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { useEffect, useState } from 'react';

import commonService from '@/api/services/commonService';
import { IconButton, Iconify } from '@/components/icon';
import { useCommon } from '@/hooks/common';

import { AddressModal } from './modal';

export default function AddressPage() {
  const uri = 'address';
  const cateName = '地址管理';
  const {
    data = [],
    ModalPros,
    doDel,
    setModalProps,
    refetch,
    handleChange,
  } = useCommon(
    { contactName: '' },
    uri,
    {
      proId: 0,
      cityId: 0,
      disId: 0,
      pcdText: '',
      address: '',
      contactName: '',
      mobile: '',
      zip: '',
      userId: 0,
    },
    '/member/address/list',
  );

  const [tree, setTree] = useState([]);

  const onCreate = (formValue: any) => {
    setModalProps((prev: any) => ({
      ...prev,
      show: true,
      type: 'add',
      title: '新增',
      formValue: {
        ...prev.formValue,
        ...formValue,
      },
    }));
  };

  const setDefault = (id: any) => {
    commonService.getCustomApi('/member/address/setDefaultAddress', { domainId: id });
    refetch();
  };

  useEffect(() => {
    commonService.getCustomApi('/member/area/getTree', {}).then((res) => {
      setTree(res);
    });
  }, []);

  const onEdit = (formValue: any) => {
    commonService.getCustomApi('/member/address/get', { domainId: formValue.id }).then((res) => {
      setModalProps((prev: any) => ({
        ...prev,
        show: true,
        type: 'edit',
        title: '编辑',
        formValue: {
          ...res,
        },
      }));
    });
  };

  const columns: ColumnsType<any> = [
    {
      title: '省/市/区(县)',
      dataIndex: 'pcdText',
      align: 'center',
      width: 250,
    },
    { title: '地址', dataIndex: 'address', align: 'center', width: 140 },
    { title: '邮编', dataIndex: 'zip', align: 'center', width: 80 },
    { title: '电话', dataIndex: 'mobile', align: 'center', width: 140 },
    { title: '收货人', dataIndex: 'contactName', align: 'center', width: 80 },
    {
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 140,
      render: (_, record) => (
        <div className="flex w-full justify-center text-gray">
          <IconButton onClick={() => onEdit(record)}>
            <Iconify icon="solar:pen-bold-duotone" size={18} />
          </IconButton>
          <Popconfirm
            title="确认删除该数据？"
            okText="确定"
            cancelText="取消"
            placement="left"
            onConfirm={() => doDel(record.id)}
          >
            <IconButton>
              <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
            </IconButton>
          </Popconfirm>
          {record.isDefault ? (
            <div
              className="flex h-[36px] w-[128px] items-center justify-center text-[#FD7901]"
              style={{
                borderRadius: '4px',
                background: '#FD790119',
                border: '1px solid #FD79014C',
              }}
            >
              默认地址
            </div>
          ) : (
            <Popconfirm
              title="确认设定为默认地址？"
              okText="确定"
              cancelText="取消"
              placement="left"
              onConfirm={() => setDefault(record.id)}
            >
              <Button className="h-[36px] w-[128px]" type="primary" ghost>
                设为默认地址
              </Button>
            </Popconfirm>
          )}
        </div>
      ),
    },
  ];

  return (
    <Space direction="vertical" size="large" className="w-full">
      <Card
        title={cateName}
        bordered={false}
        extra={
          <div className="flex flex-row gap-[10px]">
            <Button className="w-[140px]" size="large" type="primary" onClick={() => onCreate({})}>
              +新增收获地址
            </Button>
          </div>
        }
      >
        <Table
          rowKey="id"
          size="small"
          pagination={{ total: data.length }}
          scroll={{ x: 'max-content' }}
          columns={columns}
          dataSource={data}
          onChange={handleChange}
        />
      </Card>

      <AddressModal {...ModalPros} tree={tree} />
    </Space>
  );
}
